package com.balance.anole.erp.accessory.view;

import java.util.ArrayList;
import java.util.List;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

import com.balance.anole.erp.accessory.model.PrinterConfiguration;

public class PrinterConfigDialog extends Dialog {

	public PrinterConfigDialog(Shell parentShell) {
		super(parentShell);
	}

	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("打印机设置");
//		newShell.setSize(200, 600);

		// Get the resolution
		Rectangle pDisplayBounds = newShell.getDisplay().getPrimaryMonitor().getBounds();

		int nMinWidth = 200;
		int nMinHeight = 200;
		// This formulae calculate the shell's Left ant Top
		int nLeft = (pDisplayBounds.width - nMinWidth) / 2;
		int nTop = (pDisplayBounds.height - nMinHeight) / 2;

		// Set shell bounds,
		newShell.setBounds(nLeft, nTop, nMinWidth, nMinHeight);
	}

	protected void createButtonsForButtonBar(Composite parent) {

	}

	@Override
	protected Control createDialogArea(Composite parent) {
		Composite composite = (Composite) super.createDialogArea(parent);
		composite.setLayout(new GridLayout(1, false));

		Label label = new Label(composite, SWT.NONE);
		label.setText("请选择打印机");

		PrintService[] services = PrintServiceLookup.lookupPrintServices(
				null, null);
		final List<String> printerNames = new ArrayList<String>();
		String selectedPrinter = PrinterConfiguration.getPrinterName();
		int selected = 0;
		if(services != null){
			for (int i =0; i < services.length; i ++) {
				String name = services[i].getName();
				printerNames.add(name);
				if(name.equalsIgnoreCase(selectedPrinter)){
					selected = i;
				}
			}
		}

		final Combo combo = new Combo(composite, SWT.NONE);
		combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		combo.setItems(printerNames.toArray(new String[0]));
		combo.select(selected);

		Button button = new Button(composite, SWT.NONE);
		button.setText("确定");
		button.addSelectionListener(new SelectionListener(){

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
			}

			@Override
			public void widgetSelected(SelectionEvent e) {
				PrinterConfiguration.setPrinterName(printerNames.get(combo.getSelectionIndex()));
				close();
			}

		});

		return composite;
	}



}
